#!/usr/bin/env bash
# vim: fdm=marker fmr=[[[,]]] cms=\ #%s#

OS=$(uname | tr 'A-Z' 'a-z')
BIN=

usage()
{ #[[[#
    echo "Usage: svrctl start | stop | status"
} #]]]#

running()
{ #[[[#
    killall -0 $BIN 2>/dev/null
} #]]]#

command()
{ #[[[#
    local option="$1"
    case "$option" in
    "start")
        running
        if (( $? == 0 ))
        then
            echo "$BIN is running, no operation..."
            return 1
        fi
        $BIN
        sleep 1
        running
        if (( $? == 0 ))
        then
            echo "$BIN start succeed"
        else
            echo "$BIN start fail, check"
        fi
        ;;
    "stop")
        running
        if (( $? == 0 ))
        then
            killall $BIN
            sleep 1
            running
            if (( $? == 0 ))
            then
                echo "$BIN stop fail, check"
            else
                echo "$BIN stop succeed"
            fi
        else
            echo "$BIN not started"
        fi
        ;;
    "status")
        running
        if (( $? == 0 ))
        then
            case $OS in
            linux)
                ps -ef|grep -v grep|awk '$8 == "'$BIN'" { print }'
                ;;
            freebsd)
                ps aux|grep -v grep|awk '$11 == "'$BIN'" { print }'
                ;;
            esac
        else
            echo "$BIN not started"
        fi
        ;;
    *)
        usage
        ;;
    esac
} #]]]#

interact()
{ #[[[#
    local option
    echo -n "\
Options:
    1) start
    2) stop
    s) status
Choose: "
    read option
    case $option in
        1) command start ;;
        2) command stop ;;
        s) command status ;;
        *) command ? ;;
    esac
} #]]]#

main()
{ #[[[#
    local argv=$1
    local bin_path=$(dirname $0)
    if [ ${bin_path:0:1} != '/' ]
    then
        bin_path=$(pwd)/$bin_path
    fi
    cd $bin_path
    PATH=.:$PATH

    local cnfg=server.cnfg
    if [ ! -r $cnfg ]
    then
        echo "There is no config file available!"
        return 1
    fi
    BIN=$(awk '/^ *SERVER *=/ {
split($0,ar,"=");
gsub(" ","",ar[2]);
gsub("\"","",ar[2]);
print ar[2];
}' $cnfg)

    if [ -z "$argv" ]
    then
        interact
    else
        command "$argv"
    fi
} #]]]#

main $@
exit $?
